#include "tools/list.h"

List* create_list() {
    List *list = (List*)malloc(sizeof(List));
    if (!list) return NULL;

    list->array = NULL;
    list->capacity = 0;
    list->size = 0;
    return list;
}

// 自动扩容
// 使用static , 声明文件作用域，提高安全性
// 成功返回0，失败返回-1
static int expand_list(List *list) {
    const int new_capacity = list->capacity == 0 ? 4 : list->capacity * 2;
    void **new_array = realloc(list->array, new_capacity * sizeof(void*));
    if (!new_array) return -1;

    list->array = new_array;
    list->capacity = new_capacity;
    return 0;
}

int list_add(List *list, void *element) {
    if (!list) return -1;

    if (list->size >= list->capacity) {
        if (expand_list(list) != 0) return -1;
    }

    list->array[list->size++] = element;
    printf("add element %p\n", element);
    return list->size - 1;
}

void* list_get(List *list, int index) {
    if (!list || index < 0 || index >= list->size) return NULL;

    return list->array[index];
}

int list_remove(List *list, int index) {
    if (!list || index < 0 || index >= list->size) return -1;

    // 元素前移
    for (int i = index; i < list->size - 1; i++) {
        list->array[i] = list->array[i + 1];
    }
    list->size--;
    return 0;
}

void list_destroy(List *list, void (*free_func)(void*)) {
    if (!list) return;

    if (free_func) {
        for (int i = 0; i < list->size; i++) {
            free_func(list->array[i]);
        }
    }
    free(list->array);
    free(list);
}

// 查找元素，返回第一个匹配元素的索引，如果未找到则返回 -1
int list_find_ptr(List *list, void *key_ptr) {
    if (!list) return -1;

    for (int i = 0; i < list->size; i++) {
        if (list->array[i] == key_ptr) { // 直接比较指针地址
            return i;
        }
    }
    printf("find ptr\n");
    return -1;
}

